/**
 * create by ck on 2016/3/7.
 */
var list;
var packTime;
var dictTime;
$(document).ready(function () {
    list = $('#List');
    $('.xh-datagrid-toolbar').parseToolbar(afterParseToolbar);
    $('.xh-form').parseForm($('#bt_form_add, #bt_form_edit'));
    list.initDataGrid(baseUrl + 'Res/getQBankList')
        .setSelectThenEnable(['bt_list_del', 'bt_list_Pack', 'bt_list_PackOnly', 'bt_list_Dict', 'bt_list_syn', 'bt_list_push'], ['bt_list_Download']);
    /** 列表 **/
    $('#bt_list_add').click(function(){
        $.overtFun.clickAddList(list);
        $('#XHRes_QuestionBank_iQBankId').attr('readonly', false);
    });
    $('#bt_list_del').click(function () {
        var ids = list.getDataGridSelectedFields('iQBankId');         //获取List中选中的iQBankId字段值
        $.overtFun.clickDelList(ids, baseUrl + 'Res/delQBank');
    });
    if($('#bt_form_edit').length > 0){
        DataGrid.onDblClickRow = function(rowIndex, rowData){
            $.overtFun.openEditPage(rowData.iQBankId, 'XHRes_QuestionBank', callbackOpenEditPage);
        };
    }
    $('#bt_list_Pack').click(function(){
        if($(this).checkButtonDisabled()) return false;
        var ids = list.getDataGridSelectedFields('iQBankId');
        $.post(baseUrl + 'Res/packQuestionBank', {ids:ids}, function(result){                 //执行打包
            if(result.error){
                window.top.xhTop.showMessage({title: result.error, type: 'error'});
                return false;
            }
            $.each(ids.split(','), function(name, id){
                var index = list.datagrid('getRowIndex', id);
                list.datagrid('updateRow', {index:index, row:{tPackDate:'<i class="fa fa-spinner fa-spin"></i>'}});
            });
            //无正执行打包则更新时间
            if(packIds.length < 1){
                packTime = result.time;
            }
            packIds = packIds.concat(ids.split(','));                         //添加到打包题库ID数组
            packIds = packIds.unique();                                       //去重
            if(!checkFileFun) {                                                 //在执行则不再叠加
                checkFileFun = setInterval(function () {
                    checkBookFile();
                }, 1000 * 3);                                                   //3秒执行一次文件查询操作
            }
            list.dataGridClear();                                               //清空选择内容
        }, 'json');
    });
    $('#bt_list_PackOnly').click(function(){
        if($(this).checkButtonDisabled()) return false;
        var ids = list.getDataGridSelectedFields('iQBankId');
        $.post(baseUrl + 'Res/packQuestionBank', {ids: ids, packOnly: true}, function(result){                 //执行打包
            if(result.error){
                //window.top.createModal(result.error, '提示', null, 'sm');             //不成功则提示信息
                window.top.xhTop.showMessage({
                    title: result.error,
                    type: 'error'
                });
                return false;
            }
            window.top.xhTop.showMessage({
                title: '已提交打包！请自行验证是否成功！',
                type: 'success'
            });
            list.dataGridClear();                                               //清空选择内容
        }, 'json');
    });
    $('#bt_list_Dict').click(function(){
        if($(this).checkButtonDisabled()) return false;
        window.top.swal({
            title: '是否增量生成？',
            text: '（已存在字典则略过）',
            showCancelButton: true,
            cancelButtonText: '全部生成',
            confirmButtonText: '是',
            allowOutsideClick: false,
            showCloseButton: true,
            type: 'warning',
        }).then(function(isConfirm) {
            execDictQuestionBank(false);
        }, function(dismiss) {
            if(dismiss === 'close') return false;
            execDictQuestionBank(true);
        });
    });
    $('#bt_list_Download').click(function(){
        if($(this).checkButtonDisabled()) return false;
        var id = list.getDataGridSelectedField('iQBankId');
        $.post(baseUrl + 'Res/getQBankDownUrl', {id: id}, function(url){
            if(url){
                window.open(url);
            }
        });
    });
    $('#bt_list_syn').click(function(){
        if($(this).checkButtonDisabled()) return false;
        var ids = list.getDataGridSelectedFields('iQBankId');
        if(!ids) return true;
        xhExtra.askChangeStatus('Res/synQuestionBank', ids, null, '从数据中心同步？', function(){
            list.dataGridClear();
        });
    });
    //推送到盒子
    $('#bt_list_push').click(function(){
        if(xhExtra.buttonDisabled($(this))) return false;
        xhExtra.askChangeStatus('Server/pushBoxResource/1', {
            url: list.getDataGridSelectedFields('sQBDownUrl', true),
            md5: list.getDataGridSelectedFields('sQBMd5', true)
        }, null, '推送至盒子？');
    });
    /** 表单 **/
    $('#bt_form_add, #bt_form_edit').click(function () {
        $.overtFun.clickSubmitForm();
    });
    $('#bt_form_back').click(function () {
        $.overtFun.clickBackForm();
    });
    $('#bt_form_reset').click(function () {
        $.overtFun.clickResetForm();
    });
    bindImageView();
});
var checkFileFun;       //检查文件方法
var checkDictFun;       //检查字典方法
var packIds = [];       //题库打包数组
var dictIds = [];       //生成字典数组
//打开编辑窗口后回调
function callbackOpenEditPage() {
    $('#XHRes_QuestionBank_iQBankId').attr('readonly', true);
    bindImageView();
}
function execDictQuestionBank(_all)
{
    window.top.swal({
        title: '输入干扰词倍数',
        text: '（默认为3）',
        input: 'number',
        showCancelButton: true,
        cancelButtonText: '取消',
        confirmButtonText: '执行',
        allowOutsideClick: false,
        showCloseButton: true,
        type: 'warning',
    }).then(function(_maxTime) {
        if(!_all){
            _all = false;
        }
        var _rows = list.datagrid('getSelections');
        var _ids = [];
        for(var i=0; i<_rows.length; i++){
            if(_rows[i].bDict == '是'){
                _ids.push(_rows[i].iQBankId);
            }
        }
        var ids = _ids.join(',');
        if(!ids){
            window.top.xhTop.showMessage({title: '选中项不需要生成字典！', type: 'error'});
            return false;
        }
        $.post(baseUrl + 'Res/dictQuestionBank', {ids: ids, updateAll: _all, maxTime: _maxTime}, function(result){
            if(result.error){
                window.top.xhTop.showMessage({title: result.error, type: 'error'});
                return false;
            }
            $.each(ids.split(','), function(name, id){
                var index = list.datagrid('getRowIndex', id);
                list.datagrid('updateRow', {index:index, row:{bDict:'<i class="fa fa-spinner fa-spin"></i>'}});
            });
            //无正执行打包则更新时间
            if(dictIds.length < 1){
                dictTime = result.time;
            }
            dictIds = dictIds.concat(ids.split(','));                         //添加到打包题库ID数组
            dictIds = dictIds.unique();                                       //去重
            if(!checkDictFun) {                                                 //在执行则不再叠加
                checkDictFun = setInterval(function () {
                    checkBookDict();
                }, 1000 * 3);                                                   //3秒执行一次文件查询操作
            }
            list.dataGridClear();                                               //清空选择内容
        }, 'json');
    }, function(dismiss) {});
}
//检查打包文件是否成功创建
function checkBookFile() {
    if(packIds.length <= 0) return false;
    $.post(baseUrl + 'Res/checkPackFileExist', {ids : packIds.join(','), time: packTime}, function(result){
        if(result == 0) return false;
        $.each(result, function(_key, _info){
            var index = list.datagrid('getRowIndex', _info.iQBankId);
            list.datagrid('updateRow', {index:index, row:_info});
            packIds.remove(_info.iQBankId);
        });
        //if(packIds.length < 1) clearInterval(checkFileFun);                //执行完毕清空定时器
    }, 'json');
}
function checkBookDict() {
    if(dictIds.length <= 0) return false;
    $.post(baseUrl + 'Res/checkBookDictExist', {ids : dictIds.join(','), time: dictTime}, function(result){
        if(result == 0) return false;
        $.each(result, function(_key, _info){
            var index = list.datagrid('getRowIndex', _info.iQBankId);
            list.datagrid('updateRow', {index:index, row:_info});
            dictIds.remove(_info.iQBankId);
        });
        //if(packIds.length < 1) clearInterval(checkFileFun);                //执行完毕清空定时器
    }, 'json');
}

function afterParseToolbar() {
    $.overtFun.vagueSearch(list);
}

function bindImageView() {
    $('#file_cover').change(function(e) {
        var file = e.target.files[0];
        preview2(file);
    });
}
function preview1(file) {
    var img = new Image(), url = img.src = URL.createObjectURL(file);
    img.attr('style','height:200px');
    var $img = $(img);
    img.onload = function() {
        URL.revokeObjectURL(url);
        $('#cover_preview').empty().append($img)
    }
}
function preview2(file) {
    var reader = new FileReader();
    reader.onload = function(e) {
        var img = $('<img>').attr("src", e.target.result);
        img.attr('style','height:200px');
        $('#cover_preview').empty().append(img);
    };
    reader.readAsDataURL(file)
}

Array.prototype.unique = function() {
    this.sort();
    var re = [this[0]];
    for(var i = 1; i < this.length; i++)
    {
        if( this[i] !== re[re.length-1])
        {
            re.push(this[i]);
        }
    }
    return re;
};
Array.prototype.indexOf = function(val) {
    for (var i = 0; i < this.length; i++) {
        if (this[i] == val)
            return i;
    }
    return -1;
};
Array.prototype.remove = function(val) {
    var index = this.indexOf(val);
    if (index > -1) {
        this.splice(index, 1);
    }
};